package com.yunliuchain.examination.common.service.impl;

import com.yunliuchain.examination.common.service.ExportService;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class ExcelExportServiceImpl implements ExportService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public static final String SUFFIX = "xls";

    private  Workbook workbook;

    public ExcelExportServiceImpl(Workbook workbook){
        this.workbook=workbook;
    }

    @Override
    public void write(OutputStream out) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()){
            if(out != null ){
            this.workbook.write(os);
            byte[] bytes = os.toByteArray();
            out.write(bytes);
            out.flush();
            }
        } catch (IOException e) {
            logger.debug("输出文件流失败：："+e);
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                logger.debug("关闭文件流失败：："+e);
            }
        }
    }

    @Override
    public String getSuffixName() {
        return "."+this.SUFFIX;
    }

    @Override
    public String getDefaultFileName() {
        return "excel";
    }
}
